package com.example.weblending.utils;

import com.example.weblending.domain.User;
import com.example.weblending.exception.GlobalException;
import com.example.weblending.service.UserService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author helen
 * @since 2021/8/21
 */
public class JwtUtils {

    public static final long EXPIRE = 1000 * 60 * 60 * 24; //设置token过期时间
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO"; //密钥

    //生成token字符串
    public static String getJwtToken(int id, int permission){
        //构建字符串

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")

                .setSubject("lending-user")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))//设置过期时间
                .claim("id", id)//设置用户id
                .claim("permission",permission)
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();
    }

    /**
     * 判断token是否存在与有效
     * @param jwtToken jwt串
     * @return token是否有效
     */
    public static boolean checkToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 判断token是否存在与有效
     * @param request 接收到的请求
     * @return token是否有效
     */
    public static boolean checkToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("token");
            if(StringUtils.isEmpty(jwtToken)) return false;
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 根据token获取会员id
     * @param request
     * @return
     */
    public static String getMemberIdByJwtToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("token");
        if(StringUtils.isEmpty(jwtToken)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        return String.valueOf((int)claims.get("id"));
    }

    public static User checkUser(HttpServletRequest request, UserService userService){
        String id =getMemberIdByJwtToken(request);
        if(id==null){
            throw new GlobalException(403,"登录无效，请重新登录");
        }
        User user= userService.getById(id);
        if (user==null){
            throw new GlobalException(403,"该用户不存在，请重新登录");
        }
        if (user.getStatus()==1){
            throw new GlobalException(403,"您已经被封禁，请联系管理员解封");
        }
        return user;
    }
    public static User isOperator(HttpServletRequest request, UserService userService){
       User user=checkUser(request,userService);
       if (user.getPermission()==0){
           throw new GlobalException(403,"您无权限访问");
       }
       return user;
    }
}
